<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\User;
use app\common\model\UserRedpacket;
use think\Db;
use think\Exception;

class Redpacket extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\common\model\Redpacket;
    }

    public function open(){
        //获取红包uuid
        $uuid = $this->request->request('uuid');

        if (!$uuid) $this->error('i18n:192');

        //获取该红包信息，包括当前用户是否领取该红包 begin
        $map = [
            'uuid'       => $uuid,
            'expiretime' => ['>=',time()],
        ];
        $user_id = $this->auth->id;
        $redPacket = $this->model
            ->field('id,type,uuid,amount,unit_amount,send_time,expiretime')
            ->withCount(['userRedpacket'=>function($query)use($user_id){
                $query->where([
                    'user_id' => $user_id,
                ]);
            }])
            ->where($map)
            ->find();

        if (!$redPacket) $this->error('i18n:191');

        if ($redPacket['user_redpacket_count']){
			$this->error('i18n:190');
		}
        //获取该红包信息，包括当前用户是否领取该红包 end

        //判断用户是否有该红包领取资格 begin
        $prizeDrawModel = new \app\common\model\PrizeDraw();
        $where = [
            'opentime'  => ['BETWEEN',[strtotime(date('Y-m-d',$redPacket['send_time'])),$redPacket['send_time']]],
            'user_id'   => $user_id,
            'is_opened'   => 1,
        ];
        //查询是否参与抽奖 是否赢过
        $is_win = false;
        $prizeDraw = $prizeDrawModel
            ->field('id,user_id,is_win')
            ->where($where)
            ->select();

        if ($prizeDraw){
            foreach ($prizeDraw as $k => $v){
                if ($v['is_win']) {
                    $is_win = true;
                    break;
                }
            }
        }
        if (!$prizeDraw || $is_win) $this->error('i18n:189');
        //判断用户是否有该红包领取资格 end

        //添加用户红包记录 更新用户money
        $userRedpacketModel = new UserRedpacket();
        //开到的红包金额
        $amount = $redPacket['unit_amount'];
        $param = [
            'uuid'      => $uuid,
            'user_id'   => $user_id,
            'amount'    => $amount,
            'status'    => 1, //已开
            'grab_time' => time(), //开红包时间
        ];

        Db::startTrans();
        try {
            $userRedpacketModel->save($param);
            $user = User::money($amount,$user_id,'i18n:188');
            Db::commit();
        }catch (Exception $e){
            $msg = $e->getMessage();
            Db::rollback();
            $this->error($msg);
        }

        $this->success('i18n:187',$param);
    }
}